package org.shiki.hrm.filter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

	private boolean postOnly = true;

	public SmsCodeAuthenticationFilter() {
		super(new AntPathRequestMatcher("/smslogin", "POST"));
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp) throws AuthenticationException, IOException, ServletException {
		if (postOnly && !req.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + req.getMethod());
		}

		String phone = req.getParameter("phone");
		String code = req.getParameter("code");

		if (phone == null) {
			phone = "";
		}

		if (code == null) {
			code = "";
		}

		phone = phone.trim();

		SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(phone, code);

		setDetails(req, authRequest);

		return this.getAuthenticationManager().authenticate(authRequest);
	}

	private void setDetails(HttpServletRequest req, SmsCodeAuthenticationToken authRequest) {
		authRequest.setDetails(authenticationDetailsSource.buildDetails(req));
	}

	public void setPostOnly(boolean postOnly) {
		this.postOnly = postOnly;
	}
}
